frame = [0x01, 0x06, 0x02, 0x00, 0x00, 0x01]

decode = data => {
	let d = Array.from(data)				//copy source array
	let c1 = d.splice(d.length-2, 2)		//separate crc, *note: splice will change original data
	let c2 = crc(d)							//calculate crc

	if(c1[0]+c1[1]-c2[0]-c2[1])				//if the value is 0, then correct
		return 'crc error'

	let b = d.pop()							//separate encode byte
	if(b >> 5 != (b & 31) % 8)				//decode byte
		return 'code error'

	let x = d.splice(2, 1) ^ d[1]
	for(let i=2; i<d.length; i++) 
		d[i] ^= x 							//restore data

	return d
}
encode = data => {
	let d = Array.from(data)				//copy source array
	let r = Math.floor(Math.random()*123+3)	//base value of xor
	let t = r % 32							//base value of encryption
	let b = t % 8 << 5 | t 					//encode byte
	let x = d[1] ^ r 						//enhance xor value
	
	for(let i=2; i<d.length; i++) 
		d[i] ^= x 							//xor data, except before 2 bytes

	d.splice(2, 0, r)						//insert xor to index 2
	d.push(b)								//insert encode byte to last 
	return d.concat(crc(d))					//add crc and return
}
crc = d => {
    let c = 0xffff
    d.map(i => {
        let j = 8
        c ^= i
        while(j--) c = c >> 1 ^ (c & 1 ? 0xa001 : 0)
    })
    return [c & 0xff, c >> 8]
}